package cn.sciento.boot.data.change.intercept;

import java.util.List;
import java.util.Properties;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import cn.sciento.boot.data.change.handler.DataChangeBaseHandler;

@Intercepts({@Signature(type = Executor.class, method = "commit", args = {boolean.class})})
public class DataCommitInterceptor implements Interceptor {
  private List<DataChangeBaseHandler> handlerList;
  
  public DataCommitInterceptor(List<DataChangeBaseHandler> handlerList) {
    this.handlerList = handlerList;
  }
  
  public Object intercept(Invocation invocation) throws Throwable {
    Object proceed = invocation.proceed();
    doCommit();
    return proceed;
  }
  
  public Object plugin(Object target) {
    if (target instanceof Executor) {
      return Plugin.wrap(target, this);
    }
    return target;
  }
  
  public void setProperties(Properties properties) {}
  
  private void doCommit() {
    if (CollectionUtils.isNotEmpty(this.handlerList)) {
      this.handlerList.forEach(item -> item.doCommit());
    }
  }
}
